package com.a2.appa3.ui.activity;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.a2.appa3.R;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.CustomObserver;
import com.a2.appa3.model.network.HttpJsonUtils;
import com.a2.appa3.model.network.entity.req.ResRoomlist;
import com.a2.appa3.model.network.entity.req.Rescodemessage;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.shihao.library.XStatusBarHelper;

public class UserSelectActivity extends BaseActivitySimple {

    @BindView(R.id.tvback)
    TextView tvback;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.headerButton)
    TextView headerButton;
    private RecyclerView r_UserListView;
    private String roomId;//群id
    private boolean roomflag;//加人或者踢人
    private String gropid;//选中成员字符串

    private void initView() {
        r_UserListView = findViewById(R.id.recyclerView_UserSelect);
        r_UserListView.setLayoutManager(new LinearLayoutManager(this));
        r_UserListView.addItemDecoration(itemDecoration);
        tvback.setText("选择联系人");
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        headerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gropid = "";
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).isChecked()) {
                        if(roomflag){
                            gropid = gropid + list.get(i).to_id + ",";
                        }else {
                            gropid = gropid + list.get(i).user_id + ",";
                        }
                    }
                }
                if (roomflag) {
                    if (TextUtils.isEmpty(gropid)) {
                        Toast.makeText(UserSelectActivity.this, "请选择您要添加的人", Toast.LENGTH_SHORT).show();
                    } else {
                        invitation();
                    }
                } else {
                    if (TextUtils.isEmpty(gropid)) {
                        Toast.makeText(UserSelectActivity.this, "请选择您要踢出的人", Toast.LENGTH_SHORT).show();
                    } else {
                        deleteUser();
                    }
                }

            }
        });
    }

    /**
     * 踢人
     */
    private void deleteUser() {
        HttpJsonUtils.getHttpApiInstance()
                .deleteUser(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/deleteUser",
                        roomId, gropid.substring(0, gropid.length() - 1), Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Rescodemessage>() {
                    @Override
                    protected void onCustomNext(Rescodemessage resRoomInfo) {
                        if (resRoomInfo.code == 0) {
                            Toast.makeText(UserSelectActivity.this, "操作成功", Toast.LENGTH_SHORT).show();
                            initdata1();
                        } else {
                            Toast.makeText(UserSelectActivity.this, "" + resRoomInfo.msg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    /**
     * 加人
     */
    private void invitation() {
        HttpJsonUtils.getHttpApiInstance()
                .invitationUsers(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/invitationUsersAction",
                        roomId, gropid.substring(0, gropid.length() - 1), Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Rescodemessage>() {
                    @Override
                    protected void onCustomNext(Rescodemessage resRoomInfo) {
                        if (resRoomInfo.code == 0) {
                            Toast.makeText(UserSelectActivity.this, "操作成功", Toast.LENGTH_SHORT).show();
                            initdata();
                        } else if (resRoomInfo.code == 3) {
                            Toast.makeText(UserSelectActivity.this, "操作成功,请等待审核", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(UserSelectActivity.this, "" + resRoomInfo.msg, Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_userselect;
    }

    private void initInfoView() {
        r_UserListView.setAdapter(userListAdapter);
    }

    private RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
        @Override
        public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.onDraw(c, parent, state);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setColor(Color.parseColor("#FFFFFF"));
            c.drawRect(0, 0, parent.getWidth(), parent.getHeight(), paint);
            paint.setColor(Color.parseColor("#AFB1B3"));
            c.drawRect(20, 0, parent.getWidth() - 20, parent.getHeight(), paint);
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = 1;
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (Build.VERSION.SDK_INT >= 21) {
            //解决Android5.0以上，状态栏设置颜色后变灰的问题
            XStatusBarHelper.tintStatusBar(this, getResources().getColor(R.color.settingbg));
        }
        roomId = getIntent().getStringExtra("roomid");
        roomflag = getIntent().getBooleanExtra("roomflag", true);
        initView();
        initInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initInfoView();
    }


    private UserListAdapter userListAdapter;

    private List<ResRoomlist.DataBean> list;

    private void initInfo() {
        list = new ArrayList<>();
//        for (int i = 0; i < 100; i++) {
//            list.add(new TestModel("测试用户" + i));
//        }
        if (roomflag) {
            //加人
            initdata();
        } else {
            //踢人
            initdata1();
        }
        userListAdapter = new UserListAdapter();
    }

    private void initdata1() {
        HttpJsonUtils.getHttpApiInstance()
                .roomList(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/userList", roomId, Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<ResRoomlist>() {
                    @Override
                    protected void onCustomNext(ResRoomlist resRoomInfo) {
                        if (resRoomInfo.code == 0) {
                            list.clear();
                            list.addAll(resRoomInfo.data);
                            userListAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    private void initdata() {
        HttpJsonUtils.getHttpApiInstance()
                .roomList(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/invitationUsersIndex", roomId, Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<ResRoomlist>() {
                    @Override
                    protected void onCustomNext(ResRoomlist resRoomInfo) {
                        if (resRoomInfo.code == 0) {
                            list.clear();
                            list.addAll(resRoomInfo.data);
                            userListAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }


    private class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.UserSelectViewHoulder> {

        @NonNull
        @Override
        public UserSelectViewHoulder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_user_select, viewGroup, false);
            return new UserSelectViewHoulder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull UserSelectViewHoulder viewHolder, int i) {
            viewHolder.userCheck.setTag(i);

            viewHolder.userName.setText(list.get(i).username);

            Glide.with(UserSelectActivity.this).load(HttpAdress.getuseAdress()
                    + list.get(i).img).error(R.mipmap.huihuadefaultpic).into(viewHolder.userImage);
            if (roomflag) {
                if (list.get(i).is_room == 1) {
                    viewHolder.userCheck.setVisibility(View.GONE);
                } else {
                    viewHolder.userCheck.setVisibility(View.VISIBLE);
                }
            } else {
                    viewHolder.userCheck.setVisibility(View.VISIBLE);
            }

            if (list.get(i).isChecked()) {
                viewHolder.userCheck.setChecked(true);
            } else {
                viewHolder.userCheck.setChecked(false);
            }

        }

        @Override
        public int getItemCount() {
            if (list == null)
                return 0;
            return list.size();
        }

        class UserSelectViewHoulder extends RecyclerView.ViewHolder {

            private ImageView userImage;
            private TextView userName;
            private CheckBox userCheck;

            public UserSelectViewHoulder(@NonNull View itemView) {
                super(itemView);
                userImage = itemView.findViewById(R.id.imageView_Item_SelectUser);
                userName = itemView.findViewById(R.id.textView_Item_SelectUser);
                userCheck = itemView.findViewById(R.id.checkBox_Item_SelectUser);
                userCheck.setOnCheckedChangeListener(onCheckedChangeListener);
            }
        }

        private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int i = (int) buttonView.getTag();
                if (isChecked != list.get(i).isChecked()) {
                    list.get(i).setChecked(isChecked);
                    notifyDataSetChanged();
                }
            }
        };

    }

}

